<template>
    <view class="container">
        <div style="height: 20rpx;"></div>
        <div class="card">
            <div style="width: 90%;margin-left: 5%;">
                <div style="height: 10px;"></div>
                <div style="font-size: 18px;font-weight: 500;">基础信息</div>
                <div style="height: 10px;"></div>
                <u-line color="#f1f1f1"></u-line>
                <div style="height: 10px;"></div>
                <div>
                    <div>合同开始时间</div>
                    <div style="height: 15rpx;"></div>
                    <div class="borders">
                        <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
                            <input style="height: 42px;" v-model="beginData" placeholder="请选择日期" type="text" disabled>
                        </picker>
                    </div>
                </div>
                <div style="height: 10px;"></div>
                <div>
                    <div>合同结束时间</div>
                    <div style="height: 15rpx;"></div>
                    <div class="borders">
                        <picker mode="date" :value="date" :start="startDates" :end="endDates" @change="bindDateChanges">
                            <input disabled v-model="endData" style="height: 42px;" placeholder="请选择时间" type="text">
                        </picker>
                    </div>
                </div>
                <div style="height: 10px;"></div>
                <div>
                    <div>到期提醒</div>
                    <div style="height: 15rpx;"></div>
                    <u-checkbox-group v-model="checkboxValue1" placement="column" @change="checkboxChange">
                        <u-checkbox :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in checkboxList1"
                            :key="index" :label="item.name" :name="item.name">
                        </u-checkbox>
                    </u-checkbox-group>
                </div>
                <div style="height: 10px;"></div>
            </div>
        </div>

        <div v-for="(item, index) in contractArr" style="margin-top: 10px;">
            <div class="card">
                <div style="width: 90%;margin-left: 5%;">
                    <div style="height: 10px;"></div>
                    <div style="font-size: 18px;font-weight: 500;display: flex;align-items: center;justify-content: space-between;">
                        <div>有机质费用</div>
                        <image @click="delCon(index)" style="width: 50rpx;height: 50rpx;" src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/%E9%9D%92%E5%B2%9B%E5%B0%8F%E7%A8%8B%E5%BA%8F%2FFrame.png" />
                    </div>
                    <div style="height: 10px;"></div>
                    <u-line color="#f1f1f1"></u-line>
                    <div style="height: 10px;"></div>
                    <div>
                        <div>有机质名称</div>
                        <div style="height: 15rpx;"></div>
                        <div class="borders">
                            <picker @change="(event) => bindPickerChange(event, index)" :value="index"
                                :range="typeList">
                                <input style="height: 42px;" placeholder="请选择有机质" disabled v-model="item.organicType"
                                    type="text">
                            </picker>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div>
                        <div>浓度范围</div>
                        <div style="height: 15rpx;"></div>
                        <div class="borders">
                            <input type="number" :cursor-spacing="10" v-model="item.organicConcentration">
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div>
                        <div>收运价格（元/吨）</div>
                        <div style="height: 15rpx;"></div>
                        <div class="borders">
                            <input type="number" v-model="item.transportationExpense" ></input>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div>
                        <div>处理价格（元/吨）</div>
                        <div style="height: 15rpx;"></div>
                        <div class="borders">
                            <input type="number" v-model="item.treatmentExpense" />
                        </div>
                    </div>
                    <div style="height: 20px;"></div>
                </div>
            </div>
        </div>
        <div style="height: 10px;"></div>
        <div class="card">
            <div style="height: 10px;"></div>
            <div class="addBgc" @click="addType">
                <image style="width: 50rpx;height: 50rpx;"
                    src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/%E9%9D%92%E5%B2%9B%E5%B0%8F%E7%A8%8B%E5%BA%8F%2FFrame%20(1).png" />
                <div>新增有机质</div>
            </div>
            <div style="height: 10px;"></div>
        </div>
        <div style="height: 10px;"></div>
        <div class="card">
            <!-- <div style="height: 10px;"></div> -->
            <!-- <div class="newBtn1">污水合同预览</div> -->
            <div style="height: 10px;"></div>
            <div class="newBtn2" @click="lookPdf">合同预览</div>
            <div style="height: 10px;"></div>
            <div class="newBtn2" @click="sign">确认签约</div>
            <div style="height: 10px;"></div>
        </div>
        <!--  -->
        <!-- <div class="width">
            <div class="flexs">
                <div style="width: 30%;">开始时间</div>
                <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
                    <view class="uni-input">{{ beginData }}</view>
                </picker>
            </div>
            <div style="height: 20rpx;"></div>
            <div class="flexs">
                <div style="width: 30%;">结束时间</div>
                <picker mode="date" :value="date" :start="startDates" :end="endDates" @change="bindDateChanges">
                    <view class="uni-input">{{ endData }}</view>
                </picker>
            </div>
            <div style="height: 20rpx;"></div>
            <div class="flexs" style="align-items: end;">
                <div class="title">到期提醒</div>
                <div style="width: 20%;"></div>
                <u-checkbox-group v-model="checkboxValue1" placement="column" @change="checkboxChange">
                    <u-checkbox :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in checkboxList1"
                        :key="index" :label="item.name" :name="item.name">
                    </u-checkbox>
                </u-checkbox-group>
            </div>
        </div> -->
        <!-- <div style="height: 20rpx;"></div> -->
        <!-- <u-line color="#ffffff"></u-line> -->
        <!-- <div v-for="(item, index) in contractArr">
            <div style="height: 20rpx;"></div>
            <div class="width">
                <div class="form-flex">
                    <div style="width: 30%;color: #1A512C;font-weight: 500;">有机质</div>
                    <div class="borders">
                        <div style="height: 5rpx;"></div>
                        <picker @change="(event) => bindPickerChange(event, index)" :value="index" :range="typeList">
                            <input placeholder="请选择有机质" disabled v-model="item.organicType" type="text">
                        </picker>
                        <div style="height: 5rpx;"></div>
                    </div>
                </div>
                <div style="height: 20rpx;"></div>
                <div class="form-flex">
                    <div style="width: 30%;color: #1A512C;font-weight: 500;">浓度</div>
                    <div style="display: flex;align-items: center;width: 70%;">
                        <div class="borders-min" style="width: 65%;">
                            <div style="height: 5rpx;"></div>
                            <input type="number" v-model="item.organicConcentration">
                            <div style="height: 5rpx;"></div>
                        </div>
                        <div style="width: 5px;"></div>
                        <div class="borders-min" style="width: 35%;">
                            <div style="height: 5rpx;"></div>
                            <input v-model="item.ts" type="text">
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                </div>
                <div style="height: 20rpx;"></div>
                <div class="form-flex">
                    <div style="width: 30%;color: #1A512C;font-weight: 500;">处理费用</div>
                    <div style="display: flex;align-items: center;width: 70%;">
                        <div class="borders-min" style="width: 80%;">
                            <div style="height: 5rpx;"></div>
                            <input v-model="item.treatmentExpense" type="number">
                            <div style="height: 5rpx;"></div>
                        </div>
                        <div style="width: 5px;"></div>
                        <div style="width: 20%;">
                            <div style="height: 5rpx;"></div>
                            元/吨
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                </div>
                <div style="height: 20rpx;"></div>
                <div class="form-flex">
                    <div style="width: 30%;color: #1A512C;font-weight: 500;">收运费用</div>
                    <div style="display: flex;align-items: center;width: 70%;">
                        <div class="borders-min" style="width: 80%;">
                            <div style="height: 5rpx;"></div>
                            <input v-model="item.transportationExpense" type="number">
                            <div style="height: 5rpx;"></div>
                        </div>
                        <div style="width: 5px;"></div>
                        <div style="width: 20%;">
                            <div style="height: 5rpx;"></div>
                            元/吨
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                </div>
                <div style="height: 20rpx;"></div>
            </div>
            <u-line color="#ffffff"></u-line>
        </div> -->
        <!-- <div class="width">
            <div style="height: 30rpx;"></div>
            <div class="dashed" @click="lookPdf">预览完整协议</div>
            <div style="height: 30rpx;"></div>
            <div class="footer">
                <div class="button-footer" @click="cancel">取消</div>
                <div class="button-footer" @click="sign">签约</div>
            </div>
            <div style="height: 30rpx;"></div>
            <div @click="addType" style="text-align: center;font-size: 20px;">新增有机质类型</div>
            <div style="height: 30rpx;"></div>
        </div> -->
        <!-- addContract -->
        <u-overlay :show="show" @click="show = false">
            <view class="warp">
                <view class="rect" @tap.stop>
                    <view class="wrapper">
                        <view class="handCenter">
                            <canvas class="suppWriting" :disable-scroll="true" @touchstart="uploadScaleStart"
                                @touchmove="uploadScaleMove" canvas-id="suppWriting"></canvas>
                        </view>
                        <view class="handRight">
                            <view class="handTitle">客户签名</view>
                            <view class="handBtn">
                                <view class="" @click="retDraw">
                                    <view class="delBtnIcon"><u-icon name="trash" color="#F11515" size="18"></u-icon>
                                    </view>
                                    <view class="delBtn">清除画布</view>
                                </view>
                                <button @click="subCanvas" class="subBtn">确定</button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </u-overlay>
    </view>
</template>
<script>
import { generatePDF, allType, detail, addSign } from '../api/api';
import request from '../../common/request';
export default {

    data() {
        const currentDate = this.getDate({
            format: true
        })
        return {
            request: request,
            base: '',
            typeList: [],
            findType: [],
            beginData: currentDate,
            endData: currentDate,
            annex: '',
            contractArr: [
                {
                    treatmentExpense: "",
                    transportationExpense: "",
                    ts: "TS",
                    organicType: "",
                    organicConcentration: "",
                }
            ],
            checkboxValue1: [],
            // 基本案列数据
            checkboxList1: [{
                name: '到期前一天',
            },
            {
                name: '到期前三天',
            },
            {
                name: '到期前一周',
            }
            ],
            canvasName: 'suppWriting',
            ctx: '',
            startX: null,
            startY: null,
            canvasWidth: 0,
            canvasHeight: 0,
            selectColor: 'black',
            lineColor: '#1A1A1A', // 颜色
            lineSize: 5, // 笔记倍数
            MyResult: {},
            upgradeContractFlag: false,
            deliveryOrderId: null,
            show: false,
            ids: ''
        }
    },
    computed: {
        startDate() {
            return this.getDate('start');
        },
        endDate() {
            return this.getDate('end');
        },
        startDates() {
            return this.getDate('start');
        },
        endDates() {
            return this.getDate('end');
        },
    },
    methods: {
        // 删除有机质
        delCon(i){
            if(this.contractArr.length>1){
            this.contractArr.splice(i,1);

            }else{
                uni.showToast({
                    title:'必须保留一个',
                    icon:'none'
                })
            }
        },
        //预览pdf
        lookPdf() {
            let str;
            switch (JSON.stringify(this.notifyScope)) {
                case JSON.stringify(['到期前一天']):
                    // console.log(100);
                    str = '100';
                    break;
                case JSON.stringify(['到期前一天', '到期前三天']):
                    str = '110';
                    // console.log(110);
                    break;
                case JSON.stringify(['到期前一天', '到期前三天', '到期前一周']):
                    str = '111'
                    // console.log(111);
                    break;
                case JSON.stringify(['到期前三天', '到期前一周']):
                    str = '011'
                    // console.log('011');
                    break;
                case JSON.stringify(['到期前一天', '到期前一周']):
                    str = '101'
                    // console.log(101);
                    break;
                case JSON.stringify(['到期前一周']):
                    str = '001'
                    // console.log('001');
                    break;
                default:
                    break;
            }
            generatePDF({
                contract: {
                    farmId: uni.getStorageSync('userInfo').createBy,
                    beginDate: this.beginData,
                    endDate: this.endData,
                    notifyScope: str,
                },
                contractDetailList: this.contractArr
            }).then(res => {
                console.log(res.data, '预览的合同文件');
                this.annex = res.data.data;
                uni.downloadFile({ //通过uniapp的api下载下来
                    url: this.base + '/' + res.data.data,
                    success: function (res) {
                        var filePath = res.tempFilePath;
                        uni.openDocument({
                            filePath: filePath,
                            success: function (FileRes) {
                                console.log('打开文档成功');
                            }
                        });
                    }
                });

            })
        },
        bindPickerChange(e, index) {
            const value = e.detail.value;
            console.log(index, 'index');
            console.log(value);
            console.log(this.findType[value]);
            const obj = this.findType[value];
            this.contractArr[index].organicType = obj.constantName;
            // let obj = this.findType.find((item)=>item.)constantName
        },
        sign() {
            console.log(this.notifyScope);
            let str;
            switch (JSON.stringify(this.notifyScope)) {
                case JSON.stringify(['到期前一天']):
                    // console.log(100);
                    str = '100';
                    break;
                case JSON.stringify(['到期前一天', '到期前三天']):
                    str = '110';
                    // console.log(110);
                    break;
                case JSON.stringify(['到期前一天', '到期前三天', '到期前一周']):
                    str = '111'
                    // console.log(111);
                    break;
                case JSON.stringify(['到期前三天', '到期前一周']):
                    str = '011'
                    // console.log('011');
                    break;
                case JSON.stringify(['到期前一天', '到期前一周']):
                    str = '101'
                    // console.log(101);
                    break;
                case JSON.stringify(['到期前一周']):
                    str = '001'
                    // console.log('001');
                    break;
                default:
                    break;
            }

            console.log(str);
            addSign({
                contract: {
                    farmId: uni.getStorageSync('userInfo').createBy,
                    beginDate: this.beginData,
                    endDate: this.endData,
                    notifyScope: str,
                    annex: this.annex,
                    offlineSigned: 0
                },
                contractDetailList: this.contractArr
            }).then(res => {
                console.log(res.data, '填写内容成功');

                if (res.data.code == 200) {
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'success'
                    })
                    this.ids = res.data.data;
                    setTimeout(() => {
                        this.ctx = uni.createCanvasContext("suppWriting");
                        this.$nextTick(() => {
                            uni.createSelectorQuery().select('.handCenter').boundingClientRect(rect => {
                                this.canvasWidth = rect.width;
                                this.canvasHeight = rect.height;
                                /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
                                this.setCanvasBg('#fff');
                            })
                                .exec();
                        });
                        this.show = true;

                    }, 1000)
                } else {
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                }
            })
        },
        uploadScaleStart(e) {
            let that = this;
            that.startX = e.changedTouches[0].x
            that.startY = e.changedTouches[0].y
            //设置画笔参数
            //画笔颜色
            that.ctx.setStrokeStyle(that.lineColor)
            //设置线条粗细
            that.ctx.setLineWidth(that.lineSize)
            //设置线条的结束端点样式
            that.ctx.setLineCap("round") //'butt'、'round'、'square'
            //开始画笔
            that.ctx.beginPath()
        },
        // 笔迹移动
        uploadScaleMove(e) {
            let that = this;
            //取点
            let temX = e.changedTouches[0].x
            let temY = e.changedTouches[0].y
            //画线条
            that.ctx.moveTo(that.startX, that.startY)
            that.ctx.lineTo(temX, temY)
            that.ctx.stroke()
            that.startX = temX
            that.startY = temY
            that.ctx.draw(true)
        },
        /**
         * 重写
         */
        retDraw() {
            this.ctx.clearRect(0, 0, 700, 730);
            this.ctx.draw();
            //设置canvas背景
            this.setCanvasBg('#fff');
        },
        subCanvas() {
            let that = this;
            uni.showLoading({
                title: '请求中...',
                mask: true
            });
            uni.canvasToTempFilePath({
                canvasId: 'suppWriting',
                fileType: 'png',
                quality: 1, //图片质量
                success(res) {
                    console.log(res.tempFilePath, 'res');
                    // that.filePath = res.tsempFilePath;
                    // console.log(that.info,'info');
                    // console.log(that.info.id);

                    that.uploadPromise(res.tempFilePath, that.ids)
                    that.show = false;
                    uni.hideLoading();
                    return;
                }
            });
        },
        uploadPromise(url, id) {
            let that = this;
            return new Promise((resolve, reject) => {
                // console.log(this.info.id);

                let a = uni.uploadFile({
                    url: `${that.base}/farm/farmAcceptSignContract`, // 仅为示例，非真实的接口地址
                    filePath: url,
                    name: 'file',
                    formData: {
                        'id': `${id}`
                    },
                    header: {
                        Authorization: uni.getStorageSync('token')
                    },
                    success: (res) => {
                        let data = JSON.parse(res.data);
                        console.log(data, 'data');
                        if (data.code == 200) {
                            uni.showToast({
                                title: '签约成功',
                                icon: 'success'
                            })
                            setTimeout(() => {
                                uni.navigateBack({ delta: 2 });
                                that.filePath = '';
                                that.retDraw();
                                this.contractArr = [
                                    {
                                        treatmentExpense: "",
                                        transportationExpense: "",
                                        ts: "TS",
                                        organicType: "",
                                        organicConcentration: "",
                                    }
                                ];

                            }, 1000)
                        } else {
                            uni.showToast({
                                title: '失败',
                                icon: 'none'
                            })
                        }
                        // customerSign
                    }
                });
            })
        },
        //设置canvas背景色  不设置  导出的canvas的背景为透明
        //@params：字符串  color
        setCanvasBg(color) {
            /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
            //rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
            //这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
            this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4);
            // ctx.setFillStyle('red')
            this.ctx.setFillStyle(color);
            this.ctx.fill(); //设置填充
            this.ctx.draw(); //开画
        },
        editInfo() {
        },
        saveInfo() {
        },
        addType() {
            this.contractArr.push(
                {
                    treatmentExpense: "",
                    transportationExpense: "",
                    ts: "TS",
                    organicType: "",
                    organicConcentration: "",
                }
            )
        },
        checkboxChange(n) {
            console.log('change', n);
            this.notifyScope = n;
        },
        bindDateChange: function (e) {
            this.beginData = e.detail.value
        }, bindDateChanges: function (e) {
            this.endData = e.detail.value
        },
        getDate(type) {
            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        }
    },
    onShow() {
        this.base = this.request.config.baseURL;
        allType({}).then(res => {
            // console.log(res.data.data,'res');
            const { data } = res.data;
            console.log(data);
            let type = data.find((item) => item.constantName == "有机质类型");
            detail({ id: type.id }).then((res) => {
                this.typeList = res.data.data.map((item) => item.constantName);
                this.findType = res.data.data;
                console.log(this.typeList, "有机质类型");

            });
        })

    }
}
</script>
<style lang="scss">
.addBgc {
    width: 90%;
    margin-left: 5%;
    background: #dffcec;
    border-radius: 5px;
    display: flex;
    align-items: center;
    height: 50px;
    justify-content: center;
}

input {
    height: 42px
}

.warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.rect {
    width: 90vw;
    height: 90vh;
    background-color: #fff;
}

.container {
    height: 100vh;
    width: 100vw;
    background: #f3f3f3;
    overflow-y: scroll;
    color: #000000;
    font-weight: 500;
}

.width {
    width: 90%;
    margin-left: 5%;
}

.flexs {
    display: flex;
    align-items: center;
}

.card {
    padding: 10;
    background: #ffffff;
    border-radius: 7px;
    width: 90%;
    margin-left: 5%;
}

.cards {
    width: 90%;
    margin-left: 5%;

}

.flex {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.btn {
    background: #5F9F6A;
    color: #fff;
    width: 90%;
    margin-left: 5%;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.form-flex {
    display: flex;
    align-items: center;
    width: 100%;
}

.borders {
    border: 1px solid #000000;
    border-radius: 5px;
    text-align: center;
}

.borders-min {
    border: 1px solid #1A512C;
    border-radius: 5px;
    text-align: center;
}

.dashed {
    height: 20vh;
    border: 1px dashed #46A164;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.button-footer {
    width: 48%;
    height: 50px;
    background: #46A164;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    font-weight: 500;
    border-radius: 10px;
}

.wrapper {
    width: 100%;
    height: 100%;
    margin: 30rpx 0;
    overflow: hidden;
    display: flex;
    align-content: center;
    /* flex-direction: row; */
    justify-content: center;
    font-size: 28rpx;
}

.suppWriting {
    background: #fff;
    width: 100%;
    height: 90%;
}

.handRight {
    /* 	display: inline-flex;
		align-items: center;
		justify-content: space-between; */
    position: relative;
}

.handCenter {
    /* border: 4rpx dashed #e9e9e9; */
    flex: 5;
    overflow: hidden;
    box-sizing: border-box;
}

.handTitle {
    transform: rotate(90deg);
    flex: 1;
    color: #3C3F45;
    margin-top: 20px;
    font-size: 15px;
    font-style: normal;
    font-weight: 600;
}

.handBtn button {
    font-size: 28rpx;
}

.handBtn {
    position: absolute;
    bottom: 20px;
}

.delBtnIcon {
    transform: rotate(90deg);
    color: #F11515;
    font-size: 15px;
    font-style: normal;
    font-weight: 600;
    margin-right: 3px;
    margin-bottom: 1px;
}

.delBtn {
    margin-bottom: 45px;
    transform: rotate(90deg);
    color: #F11515;
    font-size: 15px;
    font-style: normal;
    font-weight: 600;
}

.subBtn {
    transform: rotate(90deg);
    color: #fff;
    margin-bottom: 30rpx;
    text-align: center;
    justify-content: center;
    border-radius: 200px;
    background: #0054A3;

}

.newBtn1 {
    width: 90%;
    margin-left: 5%;
    border-radius: 5px;
    background: #ffffff;
    border: 1px solid #000000;
    height: 45px;
    color: #000000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.newBtn2 {
    width: 90%;
    margin-left: 5%;
    border-radius: 5px;
    background: #000000;
    border: 1px solid #000000;
    height: 45px;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>